# -*- coding: utf-8 -*-
import json
import websocket
import ssl
import requests
import GCL
import confdb
from MouseCtrl import onMsg

# 网络数据包入口
def on_message(ws, message):
    print("dm msg:" + message)
    msg = json.loads(message)

    # 向服务器注册成功
    if "clientidok" in msg:
        if msg["clientidok"]==0:
            print("客户端id已被占用！是否设置新id？")
            return
        print("reg ok, id=%d" % GCL.clientid)
        if GCL.clientid != msg["clientidok"]:
            GCL.clientid = msg["clientidok"]
            confdb.cfgset("clientid", GCL.clientid)
        GCL.queueText.put("wsacode_update")
    #
    #     # getwxacode
    #     ws.send(json.dumps({"getwxacode": 0}))
    #
    # elif "getwxacode_resp" in msg:
    #     if 0 == msg['getwxacode_resp']:
    #         print(msg)


    # 服务器转发过来的信息
    elif "info" in msg:
        if msg["info"]!=GCL.clientid:
            return
        onMsg(ws,msg)




def getServerUrl():
    serverurl = confdb.cfgget("serverurl")
    if not serverurl:
        updateConf()
    print("serverurl:" + serverurl)
    return serverurl


def on_error(ws, error):
    #GCL.showInfo(error)
    print("与服务器的连接发生错误：" + error)

    # 重新获取服务器地址，并尝试连接
    confdb.cfgset("serverurl", "")


def on_close(ws):
    # GCL.ws_server.close()  #send(json.dumps({"goodbye": 0}))
    GCL.showInfo("与服务器连接关闭")


def on_open(ws):
    GCL.showInfo("等待微信扫码连接...")
    ip = GCL.getLocalIP()
    pack = json.dumps({"setclientid": GCL.clientid, "ip": ip, "port": GCL.localport})
    print("send:" + pack)
    ws.send(pack)

def clientrun():
    while(True):
        # 向配置中读取原有的id号（优先使用原有的）
        if GCL.clientid != 0:
            confdb.cfgset("clientid", GCL.clientid)
        else:
            GCL.clientid = confdb.cfggetint("clientid")

        ws_server = websocket.WebSocketApp(getServerUrl(),
                                           on_open=on_open,
                                           on_message=on_message,
                                           on_error=on_error,
                                           on_close=on_close)
        ws_server.run_forever(sslopt={"cert_reqs": ssl.CERT_NONE}, ping_interval=30, ping_timeout=10)

        print("与服务器连接的线程已退出")